package code16_反射;

import code10异常.PasswordErrorException;

import java.lang.reflect.Field;

/**
 * @author 黄衡熙
 * @version 1.0
 */
public class Test04_操作属性 {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Class c = User.class;
        // 1.获取当前类以及其父类中所有public修饰的属性
        Field[] fields = c.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("***************1*********************");

        // 2.获取当前类中所有的属性,不区分修饰符
        Field[] declaredFields = c.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println(field);
        }
        System.out.println("*****************2*******************");

        // 3.获取当前类以及其父类中指定的由public修饰的属性
        Field field = c.getField("password");
        System.out.println(field);
        field = c.getField("phone");
        System.out.println(field);
        System.out.println("***************3*********************");

        // 4.获取当前类中指定的属性,不区分修饰符
        field = c.getDeclaredField("id");
        System.out.println(field);
//        field = c.getDeclaredField("age");
//        System.out.println(field);

        System.out.println("****************4********************");
        // 为属性赋值
        User user = new User();
        Field passwordField = c.getField("password");
        passwordField.set(user, "123456");

        Field usernameField = c.getDeclaredField("username");
        usernameField.set(user, "admin");

        // 如果是private修饰的属性,需要破坏封装原则
        Field idField = c.getDeclaredField("id");
        idField.setAccessible(true);
        idField.set(user, 1);
        System.out.println(user);

        // 取值
        System.out.println("id:" + idField.get(user));
        System.out.println("username:" + usernameField.get(user));
        System.out.println("password:" + passwordField.get(user));

    }

}